package com.macro.mall.controller;

import com.github.pagehelper.PageHelper;
import com.macro.mall.annotationUtil.CurrentUserName;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.util.StringIf;
import com.macro.mall.dao.PmsCombinedProductDao;
import com.macro.mall.dao.PmsProductDao;
import com.macro.mall.dto.*;
import com.macro.mall.mapper.PmsSkuPriceLogMapper;
import com.macro.mall.mapper.PmsSkuStockMapper;
import com.macro.mall.model.*;
import com.macro.mall.service.PmsKeywordService;
import com.macro.mall.service.PmsProductService;
import com.macro.mall.service.PmsSkuStockService;
import com.macro.mall.service.UmsAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品管理Controller
 * Created by macro on 2018/4/26.
 */
@Controller
@Api(tags = "PmsProductController", description = "商品管理")
@RequestMapping("/product")
public class PmsProductController {
    @Autowired
    private PmsProductService productService;
    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private PmsProductDao productDao;
    @Autowired
    private PmsSkuStockService pmsSkuStockService;
    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Autowired
    private PmsCombinedProductDao pmsCombinedProductDao;
    @Autowired
    private PmsKeywordService keywordService;
    @Autowired
    private PmsSkuPriceLogMapper priceLogMapper;

    @ApiOperation("创建商品")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@CurrentUserName String currentUserName, @RequestBody PmsProductParam productParam) {
        UmsAdminDTO admin = this.umsAdminService.getAdminDTOByUserName(currentUserName);
        if (admin == null || admin.getStoreId() == null) {
            UmsAdmin adminByUsername = umsAdminService.getAdminByUsername(currentUserName);
            admin.setId(adminByUsername.getId());
            admin.setUserName(adminByUsername.getUsername());
        }
        Long id = productService.create(admin, productParam);
        if (id > 0L) {
            return CommonResult.success(id);
        } else if (id.equals(-2L)){
            return CommonResult.failed("请添加商品规格");
        }else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("创建组合商品")
    @RequestMapping(value = "/createCombined", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createCombined(@CurrentUserName String currentUserName, @RequestBody PmsProductParam productParam) {
        UmsAdminDTO admin = this.umsAdminService.getAdminDTOByUserName(currentUserName);
        Long id = productService.createCombined(admin, productParam);
        if (id > 0) {
            return CommonResult.success(id);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("根据商品id获取商品编辑信息")
    @RequestMapping(value = "/updateInfo/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsProductResult> getUpdateInfo(@PathVariable Long id) {
        PmsProductResult productResult = productService.getUpdateInfo(id);
        return CommonResult.success(productResult);
    }

    /**
     * 根据商品id获取商品规格信息
     * 用于审核商品时查看
     *
     * @param id 商品id
     * @return
     * @author 孙晓亮
     * @Date 2020年9月12日
     */
    @ApiOperation("根据商品id获取商品规格信息")
    @RequestMapping(value = "/gerProductSkuInfo/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsProductSkuInfoResult> gerProductSkuInfo(@PathVariable Long id) {
        List<PmsSkuStock> pmsSkuStockList = productService.gerProductSkuInfo(id);
        PmsProductSkuInfoResult pmsProductSkuInfoResult = new PmsProductSkuInfoResult();
        pmsProductSkuInfoResult.setPmsSkuStockList(pmsSkuStockList);
        return CommonResult.success(pmsProductSkuInfoResult);
    }

    /**
     * 根据商品id查询商品审核失败原因
     *
     * @param id 商品id
     * @return
     * @author 孙晓亮
     * @Data 2020年9月12日
     */
    @ApiOperation("根据商品id查询商品审核失败原因")
    @RequestMapping(value = "/getProductVertifyDetail/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<PmsProductVertifyRecord> getProductVertifyDetail(@PathVariable Long id) {
        PmsProductVertifyRecord productVertifyRecord = productService.getProductVertifyDetail(id);
        return CommonResult.success(productVertifyRecord);
    }

    @ApiOperation("更新商品")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@CurrentUserName String currentUserName, @PathVariable Long id, @RequestBody PmsProductParam productParam, BindingResult bindingResult) {
        UmsAdminDTO admin = this.umsAdminService.getAdminDTOByUserName(currentUserName);
        int count = productService.update(admin, id, productParam);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("更新组合商品")
    @RequestMapping(value = "/updateCombined/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateCombined(@CurrentUserName String currentUserName, @PathVariable Long id, @RequestBody PmsProductParam productParam, BindingResult bindingResult) {
        UmsAdminDTO admin = this.umsAdminService.getAdminDTOByUserName(currentUserName);
        int count = productService.updateCombined(admin, id, productParam);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("查询商品")
    @RequestMapping(value = "/list", method = RequestMethod.POST)//
    @ResponseBody
    public CommonResult<CommonPage<CombinedPmsProduct>> getList(@CurrentUserName String currentUserName, @RequestBody PmsProductQueryParam productQueryParam) {
        List<CombinedPmsProduct> productList = productService.list(currentUserName, productQueryParam, productQueryParam.getPageSize(), productQueryParam.getPageNum());
        CommonPage<CombinedPmsProduct> pmsProductCommonPage = CommonPage.restPage(productList);
//        List<CombinedPmsProduct> pmsProducts = pmsProductCommonPage.getList();
//        List<CombinedPmsProduct> collect = pmsProducts.stream().filter(s -> s.getType() == 1).collect(Collectors.toList());
//        if (!CollectionUtils.isEmpty(collect)) {
//            //组合商品的id集合
//            List<Long> parentProductIds = collect.stream().map(CombinedPmsProduct::getId).collect(Collectors.toList());
//            PmsSkuStockExample example = new PmsSkuStockExample();
//            example.createCriteria().andProductIdIn(parentProductIds);
//            //在pms_sku_stock表中查出规格id集合
//            List<Long> combinedIds = this.pmsSkuStockMapper.selectByExample(example).stream().map(PmsSkuStock::getId).collect(Collectors.toList());
//            Map<Long, List<CombinedPmsProduct>> sunProductMap = new HashMap<>();
//            if (parentProductIds != null && !parentProductIds.isEmpty()) {
//                List<CombinedPmsProduct> combines = this.productDao.queryProductsByCombineParentIds(parentProductIds);
//                sunProductMap = combines.stream().collect(Collectors.groupingBy(e -> Long.valueOf(String.valueOf(e.getId()))));
//            }
//            for (CombinedPmsProduct e : pmsProducts) {
//                if (e.getType() == 1) {
//                    CombinedPmsProduct combinedPmsProduct = sunProductMap.get(e.getId()).get(0);
//                    List<CombinedPmsProduct> suns = combinedPmsProduct.getCombinedProductList();
//                    e.setCombinedProductList(suns);
//                    e.setPmsSkuStock(combinedPmsProduct.getPmsSkuStock());
//                }
//            }
//        }
        return CommonResult.success(pmsProductCommonPage);
    }

    /**
     * 查询组合商品
     *
     * @param currentUserName
     * @param productQueryParam
     * @param pageSize
     * @param pageNum
     * @return
     * @author 孙晓亮
     */
    @ApiModelProperty("查询组合商品")
    @RequestMapping(value = "/getCombinedList", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<CombinedPmsProduct>> getCombinedList(@CurrentUserName String currentUserName, @RequestBody PmsProductQueryParam productQueryParam) {
        List<CombinedPmsProduct> productList = productService.list(currentUserName, productQueryParam, productQueryParam.getPageSize(), productQueryParam.getPageNum());
        CommonPage<CombinedPmsProduct> pmsProductCommonPage = CommonPage.restPage(productList);
        List<CombinedPmsProduct> pmsProducts = pmsProductCommonPage.getList();
        //组合商品的集合。缺少主商品的sku和子商品的sku集合信息
        List<CombinedPmsProduct> collect = pmsProducts.stream().filter(s -> s.getType() == 1).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            //主商品的id集合
            List<Long> parentProductIds = collect.stream().map(CombinedPmsProduct::getId).collect(Collectors.toList());
            PmsSkuStockExample example = new PmsSkuStockExample();
            example.createCriteria().andProductIdIn(parentProductIds);
            //在pms_sku_stock表中查出规格id集合
            List<PmsSkuStock> pmsSkuStockList = this.pmsSkuStockMapper.selectByExample(example);
            List<Long> parentIds = pmsSkuStockList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            //循环pms_sku_stock集合 并循环商品集合 如果两个id一致就将主商品的规格放入
            pmsSkuStockList.forEach(p -> {
                collect.forEach(z -> {
                    if (p.getProductId().equals(z.getId())) {
                        p.setStock(z.getStock());
                        z.setPmsSkuStock(p);
                    }
                });
            });
            //查询子商品信息
            PmsCombinedProductExample pmsCombinedProductExample = new PmsCombinedProductExample();
            pmsCombinedProductExample.createCriteria().andParentIdIn(parentProductIds);
            List<ProductDeitail> productDeitailList = pmsCombinedProductDao.selectByParentId(parentIds);
            collect.forEach(z -> {
                List<ProductDeitail> productDeitails = new ArrayList<>();
                productDeitailList.forEach(p -> {
                    if (p.getParentId().equals(z.getId())) {
                        productDeitails.add(p);
                    }
                });
                z.setProductDeitailList(productDeitails);
            });
        }
        return CommonResult.success(pmsProductCommonPage);
    }


    @ApiModelProperty("根据主商品id查询子商品信息")
    @RequestMapping(value = "/getCombined", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<ProductDeitail>> getCombined(@RequestParam Long id) {
        return productService.getCombined(id);
    }


    @ApiOperation("根据商品名称或货号模糊查询")
    @RequestMapping(value = "/simpleList", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<PmsProduct>> getList(@CurrentUserName String currentUserName, @RequestBody FilterParam param) {
        List<PmsProduct> productList = productService.list(currentUserName, param.getKeyWord());
        return CommonResult.success(productList);
    }

    @ApiOperation("批量修改审核状态")
    @RequestMapping(value = "/update/verifyStatus", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateVerifyStatus(@CurrentUserName String currentUserName, @RequestBody Map<String,Object> params) {
        List<Long> _ids = new ArrayList<>();
        List ids = (List)params.get("ids");
        if(ids!=null&&!ids.isEmpty()){
            for (Object id :ids) {
                _ids.add(Long.parseLong(String.valueOf(id)));
            }
        }
        Integer verifyStatus = 0;
        if(params.get("verifyStatus")!=null){
            verifyStatus = (Integer)params.get("verifyStatus");
        }
        String detail = null;
        if(params.get("detail")!=null){
            detail= (String)params.get("detail");
        }
        int count = productService.updateVerifyStatus(currentUserName, _ids, verifyStatus, detail);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 未审核的不能上架
     *
     * @param ids
     * @param publishStatus
     * @return
     * @author 高强
     */
    @ApiOperation("批量上下架")
    @RequestMapping(value = "/update/publishStatus", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePublishStatus(@RequestParam("ids") List<Long> ids,
                                            @RequestParam("publishStatus") Integer publishStatus) {
        return productService.updatePublishStatus(ids, publishStatus);
    }

    @ApiOperation("批量推荐商品")
    @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids,
                                              @RequestParam("recommendStatus") Integer recommendStatus) {
        int count = productService.updateRecommendStatus(ids, recommendStatus);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("批量设为新品")
    @RequestMapping(value = "/update/newStatus", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateNewStatus(@RequestParam("ids") List<Long> ids,
                                        @RequestParam("newStatus") Integer newStatus) {
        int count = productService.updateNewStatus(ids, newStatus);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("批量修改删除状态")
    @RequestMapping(value = "/update/deleteStatus", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateDeleteStatus(@RequestParam("ids") List<Long> ids,
                                           @RequestParam("deleteStatus") Integer deleteStatus) {
        int count = productService.updateDeleteStatus(ids, deleteStatus);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 高强
     * 查询需要入库的普通商品
     * @param currentUsername
     * @return
     * @author 高强
     * @Date 2020年9月17日
     */
    @ApiOperation("查询需要入库的普通商品")
    @RequestMapping(value = "/getInProductList", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<PmsOutProductSkuDto>> getProductSku(@CurrentUserName String currentUsername,
                                                                       @RequestBody FilterParam param) {
        CommonPage<PmsOutProductSkuDto> outProductList = productService.getOutProductList(currentUsername, param.getProductName(),
                param.getType(), param.getPageSize(), param.getPageNum(), null);
        return CommonResult.success(outProductList);
    }

    /**
     * 根据skuid查询商品信息
     *
     * @param ids
     * @return
     * @author 孙晓亮
     * @Date 2020年9月16日
     */
    @ApiModelProperty("根据skuid查询商品信息")
    @RequestMapping(value = "/getProductInfoBySkuId", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getProductInfoBySkuId(@RequestParam("ids") List<Long> ids) {
        return productService.getProductInfoBySkuId(ids);
    }


    /**
     * 查询所有出库商品列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getOutProductList", method = RequestMethod.POST)
    public CommonResult<CommonPage<PmsOutProductSkuDto>> getOutProductList(@CurrentUserName String currentUserName,
                                                                           @RequestBody FilterParam param) {
        CommonPage<PmsOutProductSkuDto> list = productService.getOutProductList(currentUserName, param.getProductName(),
                0, param.getPageSize(), param.getPageNum(), 1);
        return CommonResult.success(list);
    }

    /**
     * 根据skuid查询商品信息
     */
    @ApiModelProperty("根据skuid查询商品信息")
    @RequestMapping(value = "/getProductByids", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getProductByids(@RequestParam(value = "ids") List<Long> ids) {
        return productService.getProductByids(ids);
    }


    /**
     * 新建关键字
     *
     * @param pmsKeyword
     * @return
     */
    @RequestMapping(value = "/creatPmsKeyword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult creatPmsKeyword(@CurrentUserName String currentUsername, @RequestBody PmsKeyword pmsKeyword) {
        return keywordService.creatPmsKeyword(currentUsername, pmsKeyword);
    }

    /**
     * 查询所有关键字
     *
     * @return
     */
    @RequestMapping(value = "/getKeyword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<PmsKeyword>> getKeyword(@CurrentUserName String currentUsername,
                                                                     @RequestBody FilterParam param) {
        List<PmsKeyword> list = keywordService.getKeyword(currentUsername, param.getKeyWord());
        return CommonResult.success(list);
    }

    /**
     * 根据id查询关键字
     *
     * @return
     */
    @RequestMapping(value = "/getKeywordById", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<PmsKeyword> getKeywordById(@RequestParam Long id) {
        PmsKeyword keywordById = keywordService.getKeywordById(id);
        return CommonResult.success(keywordById);
    }

    /**
     * 删除关键字
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteKeyword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteKeyword(@RequestParam("ids") String ids) {
        int count = keywordService.deleteKeyword(ids);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 修改关键字
     *
     * @param pmsKeyword
     * @return
     */
    @RequestMapping(value = "/updatePmsKeyword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePmsKeyword(@CurrentUserName String currentUsername,
                                         @RequestBody PmsKeyword pmsKeyword) {
        return keywordService.updatePmsKeyword(currentUsername, pmsKeyword);
    }

    /**
     * 获取sku价格日志
     * @author zhouboyu
     * @Date 2020年11月13日
     * @param skuId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/getPriceLogs", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<PmsSkuPriceLog>> getPriceLogs(@RequestParam Long skuId,
                                     @RequestParam(required = false ,defaultValue = "1") Integer pageNum,
                                     @RequestParam(required = false ,defaultValue = "5") Integer pageSize
                                     ) {
        PmsSkuPriceLogExample logExample = new PmsSkuPriceLogExample();
        logExample.createCriteria().andSkuIdEqualTo(skuId);
        PageHelper.startPage(pageNum,pageSize);
        List<PmsSkuPriceLog> pmsSkuPriceLogs = this.priceLogMapper.selectByExample(logExample);
        return CommonResult.success(CommonPage.restPage(pmsSkuPriceLogs));
    }
}

